package com.mhy.tvcontrol

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.view.MotionEvent
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.widget.Button

/*
//============================蓝牙按键===========================、
/*前进  按下发出 ONA  松开ONF
  后退：按下发出 ONB  松开ONF
  左转：按下发出 ONC  松开ONF
  右转：按下发出 OND  松开ONF
  停止：按下发出 ONE  松开ONF

  数字1：按下发出 ON1  松开 ONa
  数字2：按下发出 ON2  松开 ONb
  数字3：按下发出 ON3  松开 ONc
  数字4：按下发出 ON4  松开 ONd
  数字5：按下发出 ON5  松开 ONe
  数字6：按下发出 ON6  松开 ONf
  数字7：按下发出 ON7  松开 ONg
  数字8：按下发出 ON8  松开ONh
  数字9：按下发出 ON9  松开ONi



  蓝牙程序功能是按下对应的按键执行操，松开按键就停止
*/

	//HL-1小车驱动接线定义
    #define Left_moto_go      {P0_0=1,P0_1=0;}    //左边电机向前走
	#define Left_moto_back    {P0_0=0,P0_1=1;}    //左边电机向后转
	#define Left_moto_Stop    {P0_0=0,P0_1=0;}    //左边电机停转
	#define Right_moto_go     {P0_2=1,P0_3=0;}	//右边电机向前走
	#define Right_moto_back   {P0_2=0,P0_3=1;}	//右边电机向后走
	#define Right_moto_Stop   {P0_2=0,P0_3=0;}	//右边电机停转

	#define left     'C'
    #define right    'D'
	#define up       'A'
    #define down     'B'
	#define stop     'F'
 *
 */
class BlueToothCActivity : AppCompatActivity(), SensorEventListener {
    companion object {
        private val REQUEST_CONNECT_DEVICE = 1
        private val REQUEST_ENABLE_BT = 0
        var Isconnect = false
        var sensorValueX = 0f
        var sensorValueY = 0f
    }

    private var device: BluetoothDevice? = null
    private var leftbtn: ImageButton? = null
    var mBluetoothAdapter: BluetoothAdapter? = null
    private var mBluetoothService: BluetoothService? = null
    private var rightbtn: ImageButton? = null

    //重力感应
    private var sensorManager: SensorManager? = null
    private var sensorbtn: CheckBox? = null
    private var stopbtn: ImageButton? = null
    private var upbtn: ImageButton? = null
    private var bluetoothbtn: Button? = null
    private var downbtn: ImageButton? = null
    private lateinit var button1: Button
    private lateinit var button2: Button
    private lateinit var button3: Button
    private lateinit var button4: Button
    private lateinit var button5: Button
    private lateinit var button6: Button
    private lateinit var button7: Button
    private lateinit var button8: Button
    private lateinit var button9: Button

    private var byte1 = "ON1".toByteArray()

    private var byte2 = "ON2".toByteArray()

    private var byte3 = "ON3".toByteArray()

    private var byte4 = "ON4".toByteArray()

    private var byte5 = "ON5".toByteArray()

    private var byte6 = "ON6".toByteArray()

    private var byte7 = "ON7".toByteArray()

    private var byte8 = "ON8".toByteArray()

    private var byte9 = "ON9".toByteArray()

    private var bytedown = "ONB".toByteArray()

    private var bytef = "ONF".toByteArray()

    private var byteleft = "ONC".toByteArray()

    private var byteright = "OND".toByteArray()

    private var byteup = "ONA".toByteArray()

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_blue)
//        window.setFeatureInt(7, R.layout.custom_title)
        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager?
        button1 = findViewById<Button>(R.id.button1)
        button2 = findViewById<Button>(R.id.button2)
        button3 = findViewById<Button>(R.id.button3)
        button4 = findViewById<Button>(R.id.button4)
        button5 = findViewById<Button>(R.id.button5)
        button6 = findViewById<Button>(R.id.button6)
        button7 = findViewById<Button>(R.id.button7)
        button8 = findViewById<Button>(R.id.button8)
        button9 = findViewById<Button>(R.id.button9)
        leftbtn = findViewById<ImageButton>(R.id.imageButtonleft)
        rightbtn = findViewById<ImageButton>(R.id.imageButtonright)
        upbtn = findViewById<ImageButton>(R.id.imageButtonup)
        downbtn = findViewById<ImageButton>(R.id.imageButtondown)
        stopbtn = findViewById<ImageButton>(R.id.imageButtonstop)
        sensorbtn = findViewById<CheckBox>(R.id.buttonsensor)
        bluetoothbtn = findViewById<Button>(R.id.buttonbt)
        button1.setOnTouchListener(clickListener)
        button2.setOnTouchListener(clickListener)
        button3.setOnTouchListener(clickListener)
        button4.setOnTouchListener(clickListener)
        button5.setOnTouchListener(clickListener)
        button6.setOnTouchListener(clickListener)
        button7.setOnTouchListener(clickListener)
        button8.setOnTouchListener(clickListener)
        button9.setOnTouchListener(clickListener)
        rightbtn!!.setOnTouchListener(clickListener)
        leftbtn!!.setOnTouchListener(clickListener)
        upbtn!!.setOnTouchListener(clickListener)
        downbtn!!.setOnTouchListener(clickListener)
        stopbtn!!.setOnTouchListener(clickListener)
        sensorbtn!!.setOnCheckedChangeListener { buttonView, isChecked ->
            if (!isChecked) {
                BlueToothCActivity.Isconnect = false
                if (this@BlueToothCActivity.sensorManager != null) {
                    this@BlueToothCActivity.sensorManager!!.unregisterListener(this@BlueToothCActivity)
                }
            } else if (BluetoothService.connectedThread != null) {
                this@BlueToothCActivity.sensorManager?.registerListener(
                    this@BlueToothCActivity,
                    this@BlueToothCActivity.sensorManager!!.getDefaultSensor(BlueToothCActivity.REQUEST_CONNECT_DEVICE),
                    BlueToothCActivity.REQUEST_ENABLE_BT
                )
                BlueToothCActivity.Isconnect = true
                SendDataR().start()
            } else {
                Toast.makeText(
                    this@BlueToothCActivity.getApplicationContext(),
                    "蓝牙未连接",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
        sensorbtn!!.isClickable = false
        bluetoothbtn?.setOnClickListener {
            this@BlueToothCActivity.startActivityForResult(
                Intent(
                    this@BlueToothCActivity,
                    DeviceListActivity::class.java
                ), BlueToothCActivity.REQUEST_CONNECT_DEVICE
            )
        }
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "您的手机不支持蓝牙", Toast.LENGTH_LONG).show()
        }
        if (mBluetoothAdapter?.isEnabled == false) {
            startActivityForResult(
                Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"),
                REQUEST_ENABLE_BT
            )
        } else {
            mBluetoothService = BluetoothService(this, handler)
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private val clickListener: View.OnTouchListener = View.OnTouchListener { v, event ->
        if (BluetoothService.connectedThread != null) {
            when (v.getId()) {
                R.id.imageButtonup ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byteup)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.bytef)
                        false
                    }
                    else -> false
                }
                R.id.imageButtonleft ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byteleft)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.bytef)
                        false
                    }
                    else -> false
                }
                R.id.imageButtonstop ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write("ONE".toByteArray())
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.bytef)
                        false
                    }
                    else -> false
                }
                R.id.imageButtonright ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byteright)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.bytef)
                        false
                    }
                    else -> false
                }
                R.id.imageButtondown ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.bytedown)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.bytef)
                        false
                    }
                    else -> false
                }
                R.id.button1 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte1)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONa".toByteArray())
                        false
                    }
                    else -> false
                }
                R.id.button2 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte2)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONb".toByteArray())
                        false
                    }
                    else -> false
                }
                R.id.button3 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte3)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONc".toByteArray())
                        false
                    }
                    else -> false
                }
                R.id.button4 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte4)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONd".toByteArray())
                        false
                    }
                    else -> false
                }
                R.id.button5 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte5)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONe".toByteArray())
                        false
                    }
                    else -> false
                }
                R.id.button6 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte6)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONf".toByteArray())
                        false
                    }
                    else ->
                        false
                }
                R.id.button7 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte7)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONg".toByteArray())
                        false
                    }
                    else -> false
                }
                R.id.button8 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte8)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONh".toByteArray())
                        false
                    }
                    else -> false
                }
                R.id.button9 ->
                    when (event.action) {
                    BlueToothCActivity.REQUEST_ENABLE_BT -> {
                        BluetoothService.connectedThread.write(this@BlueToothCActivity.byte9)
                        false
                    }
                    BlueToothCActivity.REQUEST_CONNECT_DEVICE -> {
                        BluetoothService.connectedThread.write("ONi".toByteArray())
                        false
                    }
                    else -> false
                }
                else -> false
            }
        } else {
            Toast.makeText(
                this@BlueToothCActivity.getApplicationContext(), "蓝牙未连接", Toast.LENGTH_LONG).show()
            false
        }
    }

    private val handler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                BluetoothService.MESSAGE_TOAST -> {
                    Toast.makeText(
                        applicationContext,
                        msg.data.getString(BluetoothService.TOAST),
                        Toast.LENGTH_LONG
                    ).show()
                    return
                }
                else -> return
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0) {
            if (resultCode == -1 && mBluetoothService == null) {
                mBluetoothService = BluetoothService(this, handler)
            }
            if (resultCode == 0) {
                Toast.makeText(
                    this,
                    "Bluetooth_untapped",
                    Toast.LENGTH_LONG
                ).show()
                finish()
            }
        }
        if (requestCode == REQUEST_CONNECT_DEVICE && resultCode == -1) {
            val address = data?.extras?.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS)
            device = mBluetoothAdapter?.getRemoteDevice(address)
            println(address)
            println(device)
            mBluetoothService?.connect(device)
            sensorbtn!!.isClickable = true
        }
    }

    override fun onSensorChanged(e: SensorEvent) {
        sensorValueX = e.values[REQUEST_ENABLE_BT]
        sensorValueY = e.values[REQUEST_CONNECT_DEVICE]
    }

    inner class SendDataR : Thread() {
        override fun run() {
            while (BlueToothCActivity.Isconnect) {
                if (BlueToothCActivity.sensorValueX > 5.0f && BlueToothCActivity.sensorValueY > -1.0f && BlueToothCActivity.sensorValueY < 3.0f) {
                    BluetoothService.connectedThread.write(this@BlueToothCActivity.bytedown)
                    try {
                        sleep(100)
                    } catch (e1: InterruptedException) {
                        e1.printStackTrace()
                    }
                }
                if (BlueToothCActivity.sensorValueX < 2.0f && BlueToothCActivity.sensorValueY > -1.0f && BlueToothCActivity.sensorValueY < 3.0f) {
                    BluetoothService.connectedThread.write(this@BlueToothCActivity.byteup)
                    try {
                        sleep(100)
                    } catch (e12: InterruptedException) {
                        e12.printStackTrace()
                    }
                }
                if (BlueToothCActivity.sensorValueY < -1.0f) {
                    BluetoothService.connectedThread.write(this@BlueToothCActivity.byteleft)
                    try {
                        sleep(100)
                    } catch (e13: InterruptedException) {
                        e13.printStackTrace()
                    }
                }
                if (BlueToothCActivity.sensorValueY > 3.0f) {
                    BluetoothService.connectedThread.write(this@BlueToothCActivity.byteright)
                    try {
                        sleep(100)
                    } catch (e14: InterruptedException) {
                        e14.printStackTrace()
                    }
                }
            }
        }
    }


    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode != 4 || event.getRepeatCount() !== 0) {
            return false
        }
        val isExit = AlertDialog.Builder(this).create()
        isExit.setTitle("系统提示")
        isExit.setMessage("确定要退出吗？")
        isExit.setIcon(R.mipmap.ic_launcher)
        val listener =
            DialogInterface.OnClickListener { dialog, which ->
                when (which) {
                    -2 -> {
                        isExit.cancel()
                        return@OnClickListener
                    }
                    -1 -> {
                        this@BlueToothCActivity.mBluetoothAdapter?.disable()
                        this@BlueToothCActivity.finish()
                        System.exit(1)
                        return@OnClickListener
                    }
                    else -> return@OnClickListener
                }
            }
        isExit.setButton("确定", listener)
        isExit.setButton2("取消", listener)
        isExit.show()
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        Isconnect = false
        if (sensorManager != null) {
            sensorManager!!.unregisterListener(this)
        }
    }
}